package agent_store

import (
	"context"
	"encoding/json"
	"xialou_platform/app/errorx"
	"xialou_platform/app/requestx"
	"xialou_platform/app/respx"
	"xialou_platform/app/tools"
	"xialou_platform/services/agent/rpc/agentClient"

	"xialou_platform/services/agent/api/internal/svc"
	"xialou_platform/services/agent/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type StoreListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewStoreListLogic(ctx context.Context, svcCtx *svc.ServiceContext) StoreListLogic {
	return StoreListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *StoreListLogic) StoreList(req *types.StoreListReq) (resp *respx.PageResp, err error) {
	agentId, err := requestx.FetchUserIdByJwt(l.ctx)
	if err != nil {
		return nil, err
	}
	list, err := l.svcCtx.AgentRpc.StoreList(l.ctx, &agentClient.StoreListReq{
		Page:     req.Page,
		PageSize: req.PageSize,
		Keyword:  req.Keyword,
		Status:   req.Status,
		Platform: req.Platform,
		AgentId:  agentId,
	})
	if err != nil {
		return nil, err
	}

	// 无数据返回空
	if list.Total == 0 {
		return respx.NewPageResp(req.Page, req.PageSize, list.Total, nil), nil
	}

	// 有数据到休闲吧查询最新商家信息
	ids := make([]string, 0)
	for _, store := range list.List {
		ids = append(ids, respx.IDFrom(store.StoreId).ToString())
	}

	reqParam := StoreBatchSearchStoresReq{
		Ids: ids,
	}

	reqStr, err := json.Marshal(reqParam)
	if err != nil {
		return nil, err
	}
	bytes, err := tools.RequestOtherPlatform(
		l.svcCtx.Config.XiuXianApi.StoreBatchSearchStores,
		"POST",
		l.svcCtx.Config.Auth.AccessSecret,
		string(reqStr),
		l.svcCtx.Config.Auth.AccessExpire,
		10000, // admin_users表 下楼系统账户的ID
	)
	if err != nil {
		return nil, err
	}

	var res StoreBatchSearchStoresResp
	err = json.Unmarshal(bytes, &res)
	if err != nil {
		logx.Infof("调用%v商家接口err：%v", req.Platform, err.Error())
		return nil, errorx.NewMsgReasonCodeError(errorx.DefaultCode, "调用商家接口err：%v", err.Error())
	}

	if res.Code != 200 {
		return nil, errorx.NewCodeReason(res.Code, res.Message)
	}

	res2 := make([]*types.StoreListResp, 0)
	for _, store := range list.List {
		for _, sd := range res.Data.List {
			if sd.Id == respx.IDFrom(store.StoreId).ToString() {
				ThumbImg := ""
				if len(sd.ThumbImgs) > 0 {
					ThumbImg = sd.ThumbImgs[0]
				}
				temp := &types.StoreListResp{
					Id:            respx.IDFrom(store.StoreId).ToString(),
					ThumbImg:      ThumbImg,
					Name:          store.Name,
					AddressDetail: sd.MapShowName,
					Status:        store.Status,
				}
				res2 = append(res2, temp)
				break
			}
		}
	}
	return respx.NewPageResp(req.Page, req.PageSize, list.Total, res2), nil
}

type StoreBatchSearchStoresReq struct {
	Ids []string `json:"ids"`
}

type StoreBatchSearchStoresResp struct {
	Code    int    `json:"code"`
	Message string `json:"message"`
	Data    struct {
		List []types.StoreBody `json:"list"`
	} `json:"data"`
}
